import { useHistory } from 'umi';
import React, { useEffect, useState } from 'react';

const Home = () => {
  const history = useHistory();
  const [scroll, setScroll] = useState(0);
  window.scrollTo(0, scroll);
  useEffect(() => {
    setScroll(window.localStorage.getItem('scroll'));

    // window.localStorage.setItem('a', 1); // 存储名为a值为1的变量
    // window.localStorage.b = 2; // 存储名为b值为2的变量
    // window.localStorage['c'] = 3;

    // 监听滚动
    window.addEventListener('scroll', handleScroll);
    // 监听窗⼝⼤⼩改变
    // window.addEventListener('resize', handleResize);

    return () => {
      console.log(1);

      // ⼀定要最后移除监听器，以防多个组件之间导致this的指向紊乱
      window.removeEventListener('scroll', handleScroll);
      // window.removeEventListener('resize', handleResize);
    };
  }, []);
  useEffect(() => {
    return () => {
      window.localStorage.setItem('scroll', scroll);
    };
  }, [scroll]);

  const handleScroll = (e) => {
    setScroll(e.srcElement.scrollingElement.scrollTop);
    // console.log(
    //   '浏览器滚动事件',
    //   e.srcElement.scrollingElement.scrollTop, // 距离滚动条顶部⾼度
    //   e.srcElement.scrollingElement.scrollHeight, // 整个⽂档⾼度
    // );
  };
  // const handleResize = (e) => {
  //   console.log('浏览器窗⼝⼤⼩改变事件', e.target.innerWidth);
  // };
  const go = () => {
    history.push('/');
  };
  return (
    <div style={{ height: 2000 }}>
      <div
        style={{
          width: 200,
          height: 200,
          background: '#CCC',
          position: 'fixed',
        }}
      >
        <button onClick={go}>123456</button>
        {scroll}
      </div>
    </div>
  );
};
export default Home;
